package com.lixiaoyao.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lixiaoyao.reggie.entity.*;
import com.lixiaoyao.reggie.service.CategoryService;
import com.lixiaoyao.reggie.service.DishFlavorService;
import com.lixiaoyao.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.yaml.snakeyaml.tokens.Token.ID.Key;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //更新数据库清除缓存
        //全部删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //精确删除
//        String keyStr = "dish_"+dishDto.getId()+"_1";
//        redisTemplate.delete(keyStr);
        dishService.saveWithFlavor(dishDto);
        return R.success("保存成功");
    }
    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page> getPage(int page,int pageSize,String name){

        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<Dish>();

        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage,lambdaQueryWrapper);
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list =  records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);

    }
    /**
     * 数据回显
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    /**
     * 菜品修改
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //更新数据库清除缓存
        //全部删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //精确删除
//        String keyStr = "dish_"+dishDto.getId()+"_1";
//        redisTemplate.delete(keyStr);
        dishService.updateWithFlavor(dishDto);
        return R.success("保存成功");
    }
    /**
     * 根据条件查询菜品列表
     */
/*    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //封装条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据菜品分类id查询菜品
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort);
        //只查询起售的
        queryWrapper.eq(Dish::getStatus,1);
        //执行查询
        List<Dish> list = dishService.list(queryWrapper);


        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> listDto = null;
        //构建redis key
        String keys = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //查询redis缓存

        listDto = (List<DishDto>) redisTemplate.opsForValue().get(keys);
        if(listDto!=null){

            return R.success(listDto);
        }

        //查询数据库
        //封装条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据菜品分类id查询菜品
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort);
        //只查询起售的
        queryWrapper.eq(Dish::getStatus,1);
        //执行查询
        List<Dish> list = dishService.list(queryWrapper);
        listDto =  list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(keys,listDto,60, TimeUnit.MINUTES);
        return R.success(listDto);
    }

}
